# -*- coding: UTF-8 -*-

from bs4 import BeautifulSoup


class DcamParser:
    """
    解析DotCommentArtMaker(v2.1.6.6)保存的xml文件
    每一个字符层的信息对应解析到一个字典中(包含index, 颜色值(十六进制), 字符, 层名称等信息)
    所有层按xml中的排列顺序存储在列表dc_items中
    """
    def __init__(self, file_path):

        self.dc_items = []
        self.idx = 0

        with open(file_path, 'r', encoding='utf-8') as f:
            self.bs = BeautifulSoup(f, 'html.parser')
            # temp = list(self.bs.descendants)

            # 找出所有层中字符数最多的一行的字符个数
            strings = [c.string if c.string is not None else '' for c in self.bs.find_all('string')]
            global_max_len = (len(max(strings, key=len, default='')))

            items = self.bs.find_all('datacommentitem')

            # 遍历每一层(DataCommentItem)
            index = 1
            for item in items:
                dc_item = {'index': index}

                # 提取颜色(RGB与Alpha通道)
                a = int(item.a.string)
                r = int(item.r.string)
                g = int(item.g.string)
                b = int(item.b.string)
                if a == 255:
                    dc_item['color'] = '{:02X}'.format(r) + '{:02X}'.format(g) \
                                       + '{:02X}'.format(b)
                else:
                    dc_item['color'] = '{:02X}'.format(r) + '{:02X}'.format(g) \
                                        + '{:02X}'.format(b) + '{:02X}'.format(a)

                dc_item['pos'] = item.pos.string
                dc_item['mode'] = item.mode.string
                dc_item['size'] = item.size.string
                dc_item['width'] = item.width.string

                # 提取一层字符
                lines = item.find_all('string')
                lines_num = len(lines)              # 字符行数
                chars = ""

                # 找出本层中字符数最多的一行
                max_len = 0
                max_line = 0
                for j, line in enumerate(lines):
                    line_str = line.string
                    if line_str is not None:
                        length = len(line_str)
                        if length > max_len:
                            max_len = length
                            max_line = j

                for j, line in enumerate(lines):
                    # 最后一行不加换行符
                    if j < lines_num - 1:
                        if line.string is not None:
                            # 本层中字符数最大的一行行尾补空格，使其字符数与其它层最大行字符数相同
                            # 以便中/右侧的锚点定位
                            if j == max_line:
                                chars += line.string + '\u3000' * (global_max_len - len(line.string))
                            else:
                                chars += line.string
                        chars += "\n"
                    else:
                        if line.string is not None:
                            chars += line.string
                        else:
                            chars += " "                # 最后一行如果为空加一个空格,以便使用下部的锚点定位等

                dc_item['chars'] = chars

                # 提取字符层的名称
                dc_item['name'] = item.find('name').string

                self.dc_items.append(dc_item)
                index += 1

        self.length = len(self.dc_items)

    def __len__(self):
        return self.length

    def __iter__(self):
        return self

    def __next__(self):
        res = None
        if self.idx < self.length:
            res = self.dc_items[self.idx]
            self.idx += 1
        else:
            raise StopIteration("超出dc_items边界")
        return res


if __name__ == "__main__":
    file_path = r"./out/美云.xml"
    dcam = DcamParser(file_path)
    print(len(dcam))
    for i in dcam:
        print(i['name'])
        print(i['color'])
    # print(next(dcam_parer))
    # print(next(dcam_parer))
